//
//  YQTopUpVC.m
//  NewRetail
//
//  Created by yuqin on 2019/7/7.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQTopUpVC.h"
#import "YQtopUpView.h"
#import "YQTopUpCell.h"
#import "YQAvertiseShowModel.h"
#import "YQTopUpBottomView.h"
#import "YQPrepaidOrderVC.h"
#import "YQWithDrawalView.h"
#import "UIImage+ImgSize.h"

@interface YQTopUpVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) YQtopUpView *topView;//1显示这个 2显示YQWithDrawalView
@property (nonatomic, strong) YQWithDrawalView *WithDrawalView;
@property (nonatomic, strong) UITableView *topTableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *imgArr;
@property (nonatomic, strong) NSMutableArray *paywayArr;
@property (nonatomic, strong) YQTopUpBottomView *bottomView;
@property (nonatomic, strong) UIButton *commitOrderBtn;

@property (nonatomic, strong) UIView *myAnimationView;//动画弹出试图
@property (nonatomic, strong) UIImageView *backImg;

@end

@implementation YQTopUpVC
{
    NSString *_amountStr;
    NSString *_selectIndex;
    NSString *_imgUrl;//接收图片
}
- (NSMutableArray *)paywayArr {
    if (!_paywayArr) {
        _paywayArr = [NSMutableArray array];
    }
    return _paywayArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = TableViewBackGroundColor;
    
    [self.iconAndTitleLeftBtn setTitle:[self.cashType integerValue] == 1?@"充值":@"提现" forState:UIControlStateNormal];
    //创建右边按钮
    [self createRightBtn];
    
    self.titleArr = @[@"微信",@"支付宝",@"银行卡"];
    self.imgArr = @[@"wechat",@"alipay",@"bankCard"];
    //获取手续费数据
    [self loadTransferData];
    //创建头部
    [self createTopView];
    //创建tableView
    [self createTableView];
    //获取绑定支付信息
//    sys/payment-way
    [self loadPaywayInfo];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(self.topTableView.mas_bottom).mas_equalTo(FIT(10));
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, 0));
    }];
}

- (void)createRightBtn {
    UIButton *rightButton = [YQViewFactory buttonWithTitle:@"订单" titleColor:WhiteColor fontSize:FIT(16) userBold:NO target:self sel:@selector(rightAction)];
    [self.headView addSubview:rightButton];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kMargin_right);
        make.centerY.mas_equalTo(self.iconAndTitleLeftBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(FIT(40), FIT(18)));
    }];
}

- (void)rightAction {
    YQPrepaidOrderVC *vc = [[YQPrepaidOrderVC alloc] init];
    vc.cashType = self.cashType;
    YQ_PUSH(vc);
}

- (void)loadTransferData {
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"sys/wallet/transferConfig") appendParameters:nil successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            self.WithDrawalView.poundageLab.text = [NSString stringWithFormat:@"手续费  %@%%",base.data[@"bkgeRate"]];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}

- (void)loadPaywayInfo {
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"sys/payment-way") appendParameters:nil successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            //获取到信息存model
            for (NSDictionary *dict in responseObject[@"data"]) {
                YQAvertiseShowModel *model = [YQAvertiseShowModel mj_objectWithKeyValues:dict];
                [self.paywayArr addObject:model];
            }
            [self.topTableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}

- (void)createTopView {
    [self.view addSubview:self.topView];
    [self.view addSubview:self.WithDrawalView];
    
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(FIT(214));
    }];
    
    [self.WithDrawalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(FIT(126));
    }];
    
    if ([self.cashType integerValue] == 1) {
        self.topView.hidden = NO;
    }else {
       self.WithDrawalView.hidden = NO;
    }
    
}

- (void)createTableView {
    [self.view addSubview:self.topTableView];
    [self.topTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo([self.cashType integerValue] == 1? self.topView.mas_bottom:self.WithDrawalView.mas_bottom).mas_equalTo(FIT(10));
        make.height.mas_equalTo(FIT(150));
    }];
    
    
    [self.view addSubview:self.commitOrderBtn];
    [self.commitOrderBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kMargin_left);
        make.bottom.mas_equalTo(-FIT(30));
        make.size.mas_equalTo(CGSizeMake(ScreenWidth-2*kMargin_left, kCommitButtonHeight));
    }];
}

- (YQtopUpView *)topView {
    if (!_topView) {
        _topView = [[YQtopUpView alloc] init];
        _topView.hidden = YES;
        _topView.ChooseButtonBlock = ^(NSString * _Nonnull amount) {
            //截取元
            amount = [amount substringWithRange:NSMakeRange(0, amount.length-1)];
            self->_amountStr = amount;
            
        };
    }
    return _topView;
}

- (YQWithDrawalView *)WithDrawalView {
    if (!_WithDrawalView) {
        _WithDrawalView = [[YQWithDrawalView alloc] init];
        _WithDrawalView.backgroundColor = WhiteColor;
        
        _WithDrawalView.hidden = YES;
        
    }
    return _WithDrawalView;
}

- (UITableView *)topTableView {
    if (!_topTableView) {
        _topTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _topTableView.scrollEnabled = NO;
        _topTableView.bounces = NO;
        _topTableView.delegate = self;
        _topTableView.dataSource = self;
        _topTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_topTableView registerNib:[UINib nibWithNibName:YQ_TopUpCell bundle:nil] forCellReuseIdentifier:YQ_TopUpCell];
    }
    return _topTableView;
}

- (YQTopUpBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[YQTopUpBottomView alloc] init];
        if ([self.cashType integerValue] == 1) {
            _bottomView.headView.theTitleLab.text = @"我的付款信息";
        }else {
            _bottomView.headView.theTitleLab.text = @"我的收款信息";
        }
        
        _bottomView.backgroundColor = WhiteColor;
        //点击查看二维码
        @weakify(self);
        _bottomView.LookBlock = ^{
            @strongify(self);
            //相当于查看大图
            //1.获取图片的宽高
            UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
            backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
            [self.view addSubview:backView];
            self.myAnimationView = backView;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchBackView:)];
            [backView addGestureRecognizer:tap];
            
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self->_imgUrl]];
            UIImage *showImage = [UIImage imageWithData:data];
            CGFloat scale;
            if (showImage.size.height > showImage.size.width) {
                scale = showImage.size.height/showImage.size.width;
            }else {
                scale = showImage.size.width/showImage.size.height;
            }
            UIImageView *bgImg = [YQViewFactory imageViewWithImage:YQ_IMAGE(@"")];
            [bgImg sd_setImageWithURL:[NSURL URLWithString:self->_imgUrl]];
            [backView addSubview:bgImg];
            self.backImg = bgImg;
            [bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.view.mas_centerX);
                make.centerY.mas_equalTo(self.view.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(ScreenWidth, ScreenWidth*scale));
            }];
            
            [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                backView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
            } completion:^(BOOL finished) {
                NSLog(@"创建完成");
            }];
            
        };
    }
    return _bottomView;
}

- (void)touchBackView:(UITapGestureRecognizer *)tap {
    [UIView performSystemAnimation:UISystemAnimationDelete onViews:@[self.myAnimationView] options:UIViewAnimationOptionLayoutSubviews animations:^{
        NSLog(@"--------");
    } completion:^(BOOL finished) {
        NSLog(@"销毁结束");
    }];
}

- (UIButton *)commitOrderBtn {
    if (!_commitOrderBtn) {
        _commitOrderBtn = [YQViewFactory buttonWithTitle:@"提交订单" titleColor:WhiteColor fontSize:kNormalButtonFont userBold:NO target:self sel:@selector(commitAction)];
        [_commitOrderBtn setBackgroundImage:YQ_IMAGE(@"commit_back") forState:UIControlStateNormal];
    }
    return _commitOrderBtn;
}

- (void)commitAction {
    //跳转到充值订单页面
    [LCProgressHUD showLoading:@"加载中..."];
    if (isEmptyString(_amountStr)) {
        _amountStr = @"2200";
    }
//    if (isEmptyString(_selectIndex)) {
//        NSString *str;
//        if ([self.cashType integerValue] == 1) {
//            str = @"请勾选付款方式";
//        }else {
//            str = @"请勾选收款方式";
//        }
//        [LCProgressHUD showMessage:str];
//        return;
//    }
    NSDictionary *dict;
    if ([self.cashType integerValue] == 1) {
        //充值
        dict = @{@"denomination":_amountStr,
                 @"payWayId":_selectIndex,
                 @"cashType":self.cashType
                 };
    }else {
        dict = @{@"denomination":self.WithDrawalView.moneyTF.text,
                 @"payWayId":_selectIndex,
                 @"cashType":self.cashType
                 };
    }
    
    [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"sys/wallet/rw") appendParameters:nil bodyParameters:dict successBlock:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [LCProgressHUD hide];
            YQPrepaidOrderVC *vc = [[YQPrepaidOrderVC alloc] init];
            vc.cashType = self.cashType;
            YQ_PUSH(vc);
        }else {            
            [LCProgressHUD showFailure:responseObject[@"msg"]];
        }
    } failureBlock:^(NSError *error) {
        
    }];
    
}

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YQTopUpCell_Height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQTopUpCell *cell = [tableView dequeueReusableCellWithIdentifier:YQ_TopUpCell forIndexPath:indexPath];
    cell.paywayImg.image = YQ_IMAGE(self.imgArr[indexPath.row]);
    cell.paywayLab.text = self.titleArr[indexPath.row];
    //有那个 那个就让点击
    cell.userInteractionEnabled = NO;
    for (YQAvertiseShowModel *model in self.paywayArr) {
        if ([model.paymentWay integerValue] == indexPath.row+1) {
            cell.userInteractionEnabled = YES;
            
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    for (YQAvertiseShowModel *model in self.paywayArr) {
        //等于啥 传啥
//        [self.view addSubview:self.bottomView];
        
        if ([model.paymentWay integerValue] == indexPath.row+1) {
            _selectIndex = StringFromLongInt(indexPath.row+1);
            _imgUrl = model.pictureUrl;
            _selectIndex = model.id;
            if ([model.paymentWay integerValue] == 1 || [model.paymentWay integerValue] == 2) {
                if ([self.cashType integerValue] == 2) {
                    self.bottomView.lookCodeLab.hidden = NO;
                    self.bottomView.codeBtn.hidden = NO;
                }
                [self.bottomView loadDataWithModel:model index:model.paymentWay];
//                [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.right.mas_equalTo(0);
//                    make.top.equalTo(self.topTableView.mas_bottom).mas_equalTo(FIT(10));
//                    make.height.mas_equalTo(FIT(145));
//                }];
                [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(FIT(145));
                }];

                
            }else if ([model.paymentWay integerValue] == 3){
                self.bottomView.lookCodeLab.hidden = YES;
                self.bottomView.codeBtn.hidden = YES;
                [self.bottomView loadDataWithModel:model index:model.paymentWay];
//                [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.right.mas_equalTo(0);
//                    make.top.equalTo(self.topTableView.mas_bottom).mas_equalTo(FIT(10));
//                    make.height.mas_equalTo(FIT(215));
//                }];
                [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(FIT(215));
                }];
            }
        }
    }
    [tableView.visibleCells enumerateObjectsUsingBlock:^(__kindof YQTopUpCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSIndexPath * targetIndexPath = [tableView indexPathForCell:obj];
//        NSLog(@"targetIndexPath.row = %ld",(long)targetIndexPath.row);
        if (targetIndexPath.row == indexPath.row) {
            [obj.isSelectBtn setImage:YQ_IMAGE(@"cz_gx_sel") forState:UIControlStateNormal];
        }else {
            [obj.isSelectBtn setImage:YQ_IMAGE(@"cz_gx_nor") forState:UIControlStateNormal];
        }
        
    }];
//    [self.topTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}


@end
